{% extends "base.html" %}

{% block title %}
    视频素材库
{% endblock %}

{% block page_title %}
    视频素材库 - 新增
{% endblock %}

{% block body %}
    <div class="form-container">
        <form id="createForm" class="edit-form" method="post" action="{{ url_for('video_library.create') }}">
            {{ form.csrf_token }}
            <div class="form-section">
                <div class="form-grid">
                    <div class="form-group">
                        {{ form.title.label(class="form-label") }} <span class="required">*</span>
                        {{ form.title(class="form-input") }}
                        <div class="form-error">
                            {% for error in form.title.errors %}{{ error }}{% endfor %}</div>
                    </div>
                    <div class="form-group">
                        {{ form.file_name.label(class="form-label") }} <span class="required">*</span>
                        <button type="button" id="uploadBtn"
                                class="bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white font-medium py-1 px-3 rounded-lg transition-all transform hover:scale-105">
                            <i class="fas fa-cloud-upload-alt mr-2"></i>上传视频
                        </button>
                        <video id="previewThumb" class="max-w-270 max-h-270 rounded-lg hidden" controls>
                            您的浏览器不支持视频播放。
                        </video>
                        <input type="hidden" id="temp_file_name" name="temp_file_name"
                               value="{{ form.temp_file_name.data }}">
                        <input type="hidden" id="file_name" name="file_name" value="{{ form.file_name.data }}">
                        <div class="form-error">
                            {% for error in form.file_name.errors %}{{ error }}{% endfor %}</div>
                    </div>
                    <div class="form-group">
                        {{ form.remarks.label(class="form-label") }}
                        {{ form.remarks(class="form-input") }}
                        <div class="form-error">
                            {% for error in form.remarks.errors %}{{ error }}{% endfor %}</div>
                    </div>
                </div>
            </div>
            <div class="form-section">
                <div class="form-actions">
                    <button type="submit" form="createForm" class="btn btn-primary">
                        <i class="fa fa-paper-plane"></i> 提交
                    </button>
                    <button type="button" id="cancelBtn" class="btn btn-cancel"
                            onclick="window.location.href='{{ url_for('video_library.page') }}'">
                        <i class="fa fa-reply"></i> 返回
                    </button>
                </div>
            </div>
        </form>

        <!-- 上传悬浮层 -->
        <div id="uploadBack" class="backdrop-blur absolute inset-0 bg-black bg-opacity-50 z-30 hidden"></div>
        <div id="uploadModal" class="fixed inset-0 z-40 hidden">

            <div class="flex items-center justify-center min-h-screen p-4">
                <div class="bg-white rounded-xl shadow-2xl p-6 w-full max-w-md fade-in">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold text-gray-800">上传视频</h3>
                        <button id="closeModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>

                    <div class="space-y-4">
                        <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
                            <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-2"></i>
                            <p class="text-gray-600 mb-4">选择要上传的视频文件</p>
                            <input type="file" id="fileInput" accept=".mp4" class="hidden">
                            <button id="selectFileBtn"
                                    class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-colors">
                                <i class="fas fa-folder-open mr-2"></i>选择文件
                            </button>
                        </div>

                        <div id="uploadProgress" class="hidden">
                            <div class="bg-gray-200 rounded-full h-2">
                                <div id="progressBar" class="bg-green-500 rounded-full transition-all h-2"
                                     style="width: 0%"></div>
                                <p class="text-sm text-gray-600 text-center -mt-3.5">上传中...</p>
                            </div>
                        </div>
                        <div id="uploadResult" class="hidden">
                            <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                                <i class="fas fa-check text-green-500 mr-2"></i>
                                <span id="resultMessage" class="text-green-700"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        // DOM元素
        const uploadModal = document.getElementById('uploadModal');
        const uploadBack = document.getElementById('uploadBack');
        const uploadBtn = document.getElementById('uploadBtn');
        const closeModal = document.getElementById('closeModal');
        const fileInput = document.getElementById('fileInput');
        const selectFileBtn = document.getElementById('selectFileBtn');
        const uploadProgress = document.getElementById('uploadProgress');
        const progressBar = document.getElementById('progressBar');
        const uploadResult = document.getElementById('uploadResult');
        const resultMessage = document.getElementById('resultMessage');
        const previewThumb = document.getElementById('previewThumb');
        const urlField = document.getElementById('file_name');
        const tempFileName = document.getElementById('temp_file_name');

        // 显示上传模态框
        uploadBtn.addEventListener('click', () => {
            uploadModal.classList.remove('hidden');
            uploadBack.classList.remove('hidden');
        });

        // 关闭上传模态框
        closeModal.addEventListener('click', () => {
            uploadModal.classList.add('hidden');
            uploadBack.classList.add('hidden');
            resetUploadState();
        });


        // 点击背景关闭
        uploadModal.addEventListener('click', (e) => {
            if (e.target === uploadModal) {
                uploadModal.classList.add('hidden');
                uploadBack.classList.add('hidden');
                resetUploadState();
            }
        });

        // 选择文件
        selectFileBtn.addEventListener('click', () => {
            fileInput.click();
        });

        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];

            if (file) {
                // 显示上传进度
                uploadProgress.classList.remove('hidden');

                // 模拟上传进度
                let progress = 0;
                const progressInterval = setInterval(() => {
                    progress += 5;
                    progressBar.style.width = progress + '%';

                    if (progress >= 100) {
                        clearInterval(progressInterval);
                        performUpload(file);
                    }
                }, 50);
            }
        });

        // 执行上传
        function performUpload(file) {
            try {
                const formData = new FormData();
                formData.append('file', file);

                axios.post("{{ url_for('public.temp_upload_video') }}", formData, {
                    headers: {
                        'X-CSRFToken': document.getElementById('csrf_token').value,
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(response => {
                    if (response.status === 200) {
                        // 上传成功
                        const result = response.data;
                        showUploadResult('success', `上传成功！文件地址：${result.name}`);

                        // 更新URL字段和预览图片
                        urlField.value = result.name;
                        tempFileName.value = result.temp_name;
                        previewThumb.src = result.url;
                        previewThumb.classList.remove('hidden');

                        // 1秒后自动关闭模态框
                        setTimeout(() => {
                            uploadModal.classList.add('hidden');
                            uploadBack.classList.add('hidden');
                            resetUploadState();
                        }, 3000);
                    } else {
                        showUploadResult('error', `上传失败：${response.data.error}`);
                    }
                }).catch(error => {
                    console.error('上传失败:', error);
                    showUploadResult('error', `上传失败：${error.response.data.error}`);
                });

            } catch (error) {
                showUploadResult('error', `网络错误：${error.message}`);
            }
        }

        // 显示上传结果
        function showUploadResult(type, message) {
            uploadProgress.classList.add('hidden');
            uploadResult.classList.remove('hidden');

            if (type === 'success') {
                uploadResult.className = 'bg-green-50 border border-green-200 rounded-lg p-4';
                resultMessage.className = 'text-green-700';
            } else {
                uploadResult.className = 'bg-red-50 border border-red-200 rounded-lg p-4';
                resultMessage.className = 'text-red-700';
            }
            resultMessage.textContent = message;
        }

        // 重置上传状态
        function resetUploadState() {
            fileInput.value = '';
            uploadProgress.classList.add('hidden');
            uploadResult.classList.add('hidden');
            progressBar.style.width = '0%';
        }
    </script>
{% endblock %}